﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Security.Cryptography;
namespace FBStockTransfer {
    public class ConnectionObject {
        private TcpClient tc;
        private NetworkStream tcS;

        private EndianBinaryWriter bw;
        private EndianBinaryReader br;

        private Socket sock;
        private IPEndPoint ipep;
        private IPAddress ipAddr;

        /**
         * Create the server connection
         */
        public ConnectionObject() {
            tc = new TcpClient("localhost", 28192);

            tcS = tc.GetStream();
           
            bw = new EndianBinaryWriter(new BigEndianBitConverter(), tcS);
            br = new EndianBinaryReader(new BigEndianBitConverter(), tcS);
        }

        /**
         * Send the XML request string
         */
        public String sendCommand(string command) {
            try {
                bw = new EndianBinaryWriter(new BigEndianBitConverter(), tcS);
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                byte[] bytes = encoding.GetBytes(command);
                bw.Write(bytes.Length);
                bw.Write(bytes);
                
                bw.Flush();
                br = new EndianBinaryReader(new BigEndianBitConverter(), tcS);
                int i = br.ReadInt32();
                
                byte[] bytess = new byte[i];
                br.Read(bytess, 0, i);
                String response = encoding.GetString(bytess, 0, i);

                return response;
            } catch (Exception) {

                return "";
            }
        }
        public static String createLoginXml(string username, string password)
        {
            System.Text.StringBuilder buffer = new System.Text.StringBuilder("<FbiXml><Ticket/><FbiMsgsRq><LoginRq><IAID>");
            buffer.Append("222");
            buffer.Append("</IAID><IAName>");
            buffer.Append("C Sharp Sample");
            buffer.Append("</IAName><IADescription>");
            buffer.Append("Sample Coding for C Sharp");
            buffer.Append("</IADescription><UserName>");
            buffer.Append(username);
            buffer.Append("</UserName><UserPassword>");

            MD5 md5 = MD5CryptoServiceProvider.Create();
            byte[] encoded = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(password));
            string encrypted = Convert.ToBase64String(encoded, 0, 16);
            buffer.Append(encrypted);
            buffer.Append("</UserPassword></LoginRq></FbiMsgsRq></FbiXml>");

            return buffer.ToString();
        }

    }
}
